<template>
  <div class="search">
    <Card>
      <Row @keydown.enter.native="handleSearch">
        <Form
          ref="searchForm"
          :model="searchForm"
          inline
          :label-width="70"
          class="search-form"
        >
          <Form-item label="手机号" prop="mobile">
            <Input
              type="text"
              v-model="searchForm.mobile"
              placeholder="请输入手机号"
              :maxlength="11"
              clearable
              style="width: 200px"
            />
          </Form-item>
          <Form-item label="昵称" prop="nickName">
            <Input
              type="text"
              v-model="searchForm.nickName"
              placeholder="请输入昵称"
              :maxlength="10"
              clearable
              style="width: 200px"
            />
          </Form-item>
          <Button
            @click="handleSearch"
            class="search-btn"
            type="primary"
            icon="ios-search"
            >搜索</Button
          >
        </Form>
      </Row>
      <Row v-if="action" class="operation padding-row">
        <Button @click="handleAdd" type="error">新增会员</Button>
        <Button @click="resetPwd">重置密码</Button>
      </Row>
      <Table
        :loading="loading"
        border
        :columns="columns"
        sortable="custom"
        class="mt_10"
        :data="data"
        ref="table"
        @on-selection-change="changeSelect"
      ></Table>
      <Row type="flex" justify="end" class="mt_10">
        <Page
          :current="searchForm.pageNumber"
          :total="total"
          :page-size="searchForm.pageSize"
          @on-change="changePage"
          @on-page-size-change="changePageSize"
          :page-size-opts="[10, 20, 50]"
          size="small"
          show-total
          show-elevator
          show-sizer
        ></Page>
      </Row>
    </Card>

    <!-- 新增、编辑模态框 -->
    <Modal v-model="editFlag" :title="editForm.id ? '编辑' : '新增'">
      <Form ref="editForm" :model="editForm" :rules="rules" :label-width="100">
        <FormItem label="账号/手机号" prop="mobile" style="width: 100%">
          <Input
            v-model="editForm.mobile"
            :maxlength="11"
            placeholder="请输入账号/手机号"
          />
        </FormItem>
        <FormItem v-if="!editForm.id" label="密码" prop="password" style="width: 100%">
          <Input type="password" v-model="editForm.password" placeholder="请输入密码" />
        </FormItem>
        <FormItem label="头像" style="width: 100%">
          <Upload
            action
            type="drag"
            ref="upload"
            :max-size="2 * 1024"
            :show-upload-list="false"
            :before-upload="beforeUpload"
            accept=".jpg, .jpeg, gif, .png"
            :format="['jpg', 'jpeg', 'gif', 'png']"
            style="display: inline-block; width: 58px"
          >
            <div style="width: 58px; height: 58px; line-height: 58px">
              <img
                v-if="editForm.face"
                :src="editForm.face"
                style="width: 100%; height: 100%"
              />
              <Icon v-else type="md-person" size="20" />
            </div>
          </Upload>
        </FormItem>
        <FormItem label="昵称" prop="nickName" style="width: 100%">
          <Input v-model="editForm.nickName" :maxlength="10" placeholder="请输入昵称" />
        </FormItem>
        <FormItem label="性别" prop="sex" style="width: 100%">
          <Select
            v-model="editForm.sex"
            placeholder="请选择"
            clearable
            style="width: 100%"
          >
            <Option value="1">男</Option>
            <Option value="0">女</Option>
          </Select>
        </FormItem>
        <FormItem label="生日" prop="birthday" style="width: 100%">
          <DatePicker
            type="date"
            v-model="editForm.birthday"
            format="yyyy-MM-dd"
            :options="bornOption"
            placeholder="请选择生日"
            style="width: 100%"
          />
        </FormItem>
        <FormItem label="身高" prop="height" style="width: 100%">
          <Input v-model="editForm.height" placeholder="请输入身高">
            <span slot="append">cm</span>
          </Input>
        </FormItem>
        <FormItem label="体重" prop="weight" style="width: 100%">
          <Input v-model="editForm.weight" placeholder="请输入体重">
            <span slot="append">kg</span>
          </Input>
        </FormItem>
        <FormItem v-if="editForm.id" label="BMI" prop="bmi" style="width: 100%">
          <Input v-model="editForm.bmi" disabled> </Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="editFlag = false">取消</Button>
        <Button type="primary" @click="submitForm">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import * as API_Membership from "@/api/membership.js";
import * as RegExp from "@/libs/RegExp.js";

export default {
  name: "membership",
  data() {
    return {
      loading: false, // 加载状态
      searchForm: {
        // 请求参数
        pageNumber: 1,
        pageSize: 10,
        nickName: null, // 昵称
        mobile: null, // 手机号
      },
      selectList: [], // 多选数据
      editFlag: false, // 编辑弹窗
      editForm: {
        // 编辑表单
        id: "",
        mobile: "", // 账号/手机号
        username: "", // 用户名
        password: "", // 密码
        face: "", // 头像
        nickName: "", // 昵称
        sex: "1", // 性别 1男，0女
        birthday: "", // 生日
        height: "", // 身高
        weight: "", // 体重
        bmi: "", //BMI值
      },
      rules: {
        // 验证规则
        mobile: [
          { required: true, message: "请输入账号/手机号" },
          { pattern: RegExp.mobile, message: "请输入正确的手机号" },
        ],
        password: [{ required: true, message: "请输入密码" }],
      },
      bornOption: {
        // 生日限制
        disabledDate: (date) => {
          let now = new Date().getTime();
          return date && date.valueOf() > now;
        },
      },
      columns: [
        // 表头
        { type: "selection", width: 60, align: "center" },
        { title: "账号/手机号", minWidth: 120, key: "mobile" },
        {
          title: "角色",
          minWidth: 120,
          render: (h, params) => {
            let label = "--";
            let color = "warning";
            if (params.row.haveStore) {
              label = "商家";
              color = "error";
            } else if (params.row.userType == 0) {
              label = "学生";
              color = "blue";
            } else if (params.row.userType == 1) {
              label = "教师";
              color = "red";
            } else if (params.row.userType == 2) {
              label = "社会人员";
              color = "orange";
            }
            return h("Tag", { props: { color } }, label);
          },
        },
        {
          title: "头像",
          minWidth: 140,
          render: (h, params) => {
            let res = [];
            if (params.row.face) {
              res.push(
                h("img", {
                  attrs: { src: params.row.face },
                  style: { width: "100px" },
                })
              );
            }
            return res;
          },
        },
        { title: "昵称", key: "nickName", minWidth: 120, tooltip: true },
        {
          title: "性别",
          minWidth: 120,
          render: (h, params) => {
            return h("div", [h("span", {}, params.row.sex == "1" ? "男" : "女")]);
          },
        },
        { title: "出生年月", key: "birthday", minWidth: 120, tooltip: true },
        { title: "身份证号", key: "idCard", minWidth: 180, tooltip: true },
        { title: "身高(cm)", key: "height", minWidth: 120, tooltip: true },
        { title: "体重(kg)", key: "weight", minWidth: 120, tooltip: true },
        { title: "注册时间", key: "createTime", minWidth: 180, tooltip: true },
        {
          title: "状态",
          minWidth: 130,
          render: (h, params) => {
            return h("div", [
              h("div", {
                style: {
                  display: "inline-block",
                  width: "8px",
                  height: "8px",
                  backgroundColor: params.row.disabled ? "#68CABE" : "#FF5C58",
                  marginRight: "6px",
                  borderRadius: "50%",
                },
              }),
              h("span", {}, params.row.disabled ? "启用" : "禁用"),
            ]);
          },
        },
        {
          title: "操作",
          align: "center",
          width: 200,
          fixed: "right",
          render: (h, params) => {
            let func = [];
            if (!this.action) {
              func.push(this.btnDom(h, null, "选择", "callback", params));
            } else {
              func.push(this.btnDom(h, "info", "查看", "handleView", params));
              func.push(this.btnDom(h, "info", "编辑", "editPerm", params, true));
              let label = params.row.disabled ? "禁用" : "启用";
              func.push(this.btnDom(h, null, label, "handleStatus", params));
            }
            return h(
              "div",
              { style: { display: "flex", justifyContent: "center" } },
              func
            );
          },
        },
      ],
      data: [], // 表单数据
      total: 0, // 表单数据总数
    };
  },
  props: {
    action: {
      type: Boolean,
      default: true,
    },
  },
  watch: {
    editFlag(v) {
      if (!v) {
        this.editForm = {
          id: "",
          mobile: "", // 账号/手机号
          username: "", // 用户名
          password: "", // 密码
          face: "", // 头像
          nickName: "", // 昵称
          sex: 1, // 性别 1男，0女
          birthday: "", // 生日
          height: "", // 身高
          weight: "", // 体重
          bmi: "", //BMI值
        };
        setTimeout(() => {
          this.$refs.editForm.resetFields();
        }, 0);
      }
    },
  },
  methods: {
    // 回调给父级
    callback(val) {
      this.$emit("callback", val);
    },
    // 分页 改变页码
    changePage(v) {
      this.searchForm.pageNumber = v;
      this.getData();
    },
    // 分页 改变页数
    changePageSize(v) {
      this.searchForm.pageSize = v;
      this.searchForm.pageNumber = 1;
      this.getData();
    },
    // 搜索
    handleSearch() {
      this.searchForm.pageNumber = 1;
      this.searchForm.pageSize = 10;
      this.getData();
    },
    // 多选
    changeSelect(e) {
      this.selectList = e;
    },
    // 按钮
    btnDom(h, type = null, label = "", method, params, ghost = false) {
      return h(
        "Button",
        {
          props: { type, size: "small", ghost },
          style: { marginRight: "5px" },
          on: {
            click: () => {
              this[method](params.row);
            },
          },
        },
        label
      );
    },
    // 新增
    handleAdd() {
      this.editFlag = true;
    },
    // 修改
    editPerm(v) {
      this.editFlag = true;
      Object.keys(this.editForm).map((i) => {
        this.editForm[i] = v[i] || v[i] == 0 ? v[i] : "";
      });
      delete this.editForm.password;
    },
    // 查看
    handleView(v) {
      this.$router.push({
        name: "member-detail",
        query: { id: v.id },
      });
    },
    // 自定义上传
    beforeUpload(file) {
      let typeList = [".jpg", ".jpeg", ".png"];
      if (!typeList.some((i) => file.name.lastIndexOf(i) != -1)) {
        this.$Message.warning("请检查上传文件格式");
        return;
      }
      if (file.size / 1024 > 2 * 1024) {
        this.$Message.warning("图片大小不能超过2MB");
        return;
      }
      const formData = new FormData();
      formData.append("file", file);
      API_Membership.postUpload(formData).then((res) => {
        if (res.success) {
          this.editForm.face = res.result;
        }
      });
      return false;
    },
    // 重置密码
    resetPwd() {
      this.$Modal.confirm({
        title: "确认重置",
        content:
          "<p>您确认要重置所选的" +
          this.selectList.length +
          "条用户数据密码为【123456】？</p>",
        onOk: () => {
          let ids = this.selectList
            .map((i) => {
              return i.id;
            })
            .join(",");
          API_Membership.getResetPwd(ids).then((res) => {
            if (res.success) {
              this.$Message.success("重置成功");
              this.getData();
            }
          });
        },
      });
    },
    //提交
    submitForm() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          if (this.editForm.height && this.editForm.weight) {
            let w = parseFloat(this.editForm.weight);
            let h = parseFloat(this.editForm.height) / 100;
            this.editForm.bmi = parseFloat(w / (h * h), 2).toFixed(2);
          }
          let date = this.editForm.birthday;
          if (date) {
            this.editForm.birthday = new Date(date).Format("yyyy-MM-dd");
          }
          if (this.editForm.id) {
            API_Membership.putMemberUpdate(this.editForm).then((res) => {
              if (res.success) {
                this.$Message.success("修改成功");
                this.editFlag = false;
                this.getData();
              }
            });
          } else {
            this.editForm.password = this.md5(this.editForm.password);
            API_Membership.postMemberAdd(this.editForm).then((res) => {
              if (res.success) {
                this.$Message.success("添加成功");
                this.editFlag = false;
                this.getData();
              }
            });
          }
        }
      });
    },
    //禁-启 用状态
    handleStatus(v) {
      let params = {
        memberIds: [v.id],
        disabled: !v.disabled,
      };
      this.$Modal.confirm({
        title: "确认" + (v.disabled ? "禁用" : "启用"),
        content:
          "<p>您确认要" + (v.disabled ? "禁用" : "启用") + "用户" + v.username + "？</p>",
        onOk: () => {
          API_Membership.putMemberStatus(params).then((res) => {
            if (res.success) {
              this.$Message.success((v.disabled ? "禁用" : "启用") + "成功");
              this.getData();
            }
          });
        },
      });
    },
    //查询会员列表
    getData() {
      this.loading = true;
      API_Membership.getMemberPage(this.searchForm)
        .then((res) => {
          if (res.success) {
            this.data = res.result.records;
            this.total = parseInt(res.result.total);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
  },
  mounted() {
      if (!this.action) {
        let index = this.columns.findIndex(i => i.type == "selection");
        if (index != -1) {
          this.columns.splice(index, 1);
        }
      }
    this.getData();
  },
};
</script>
<style lang="scss" scoped>
::v-deep .ivu-table-wrapper {
  width: 100%;
}
::v-deep .ivu-card {
  width: 100%;
}
.face {
  width: 60px;
  height: 60px;
  border-radius: 50%;
}
</style>
